package com.tedu.weibo.controller;

import com.tedu.weibo.mapper.UserMapper;
import com.tedu.weibo.pojo.dto.UserLoginDTO;
import com.tedu.weibo.pojo.dto.UserRegDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/reg")
    public int reg(@RequestBody UserRegDTO userRegDTO) {
        System.out.println(userRegDTO);

        String username = userRegDTO.getUsername();
        User findUser = userMapper.selectByUsername(username);
        if (findUser != null) {
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return 1;
    }

    @PostMapping("/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session) {
        System.out.println(userLoginDTO);
        User user = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (user != null) {
            if (user.getPassword().equals(userLoginDTO.getPassword())) {
                session.setAttribute("user", user);
                return 1;
            } else {
                return 2;
            }
        } else {
            return 3;
        }
    }

    @GetMapping("/currentUser")
    public UserVO currentUser(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return null;
        } else {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }
    }
    @GetMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}